﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;
using System.IO;
using System.Windows.Forms;

namespace Dzzzr
{
	/// <summary>
	/// Image editor
	/// </summary>
	public class ImageEditor : UITypeEditor
	{
		/// <summary>
		/// Edit Value
		/// </summary>
		/// <param name="context"></param>
		/// <param name="provider"></param>
		/// <param name="value"></param>
		/// <returns></returns>
		public override Object EditValue(ITypeDescriptorContext context, IServiceProvider provider, Object value)
		{
			if ((context != null) && (provider != null))
			{
				IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

				if (svc != null)
				{
					using (DetailFormImageEditor dfie = new DetailFormImageEditor())
					{
						if (value is System.Data.Linq.Binary
							&& (value as System.Data.Linq.Binary) != null
							&& (value as System.Data.Linq.Binary).Length > 0)
						{
							byte[] data = (value as System.Data.Linq.Binary).ToArray();
							dfie.ImageStream.SetLength(data.Length);
							dfie.ImageStream.Seek(0, SeekOrigin.Begin);
							dfie.ImageStream.Write(data, 0, data.Length);
						}
						if (svc.ShowDialog(dfie) == DialogResult.OK)
						{
							if (dfie.ImageStream.Length == 0)
								value = null;
							else
							{
								dfie.ImageStream.Seek(0, SeekOrigin.Begin);
								value = new System.Data.Linq.Binary(dfie.ImageStream.ToArray());
							}
						}
					}
				}
			}

			return base.EditValue(context, provider, value);
		}

		/// <summary>
		/// Edit style
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			if (context != null)
				return UITypeEditorEditStyle.Modal;
			else
				return base.GetEditStyle(context);
		}
	}
}
